package com.weishuang.monitor.leader.commons.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * 树形结构数据工具类
 * @param <T>
 */
public class TreeUtils<T> {

    /**
     * build函数方法，用于存放函数在构造树的时候可以获取关键数据
     * @param reservoirOrganizationStructureClass
     * @param <T>
     * @return
     */
    public static <T> TreeFunctionImpl<T> builder(Class<T> reservoirOrganizationStructureClass) {
        return new TreeFunctionImpl<T>(new TreeUtils<T>());
    }

    /**
     * 构造树数据
     *  WARN 42行：这个地方不好创建对象放入，所以树结构对象默认创建子数组
     * @param list
     * @param tTreeFunction
     * @return
     */
    public List<T> build(List<T> list, TreeFunctionImpl<T> tTreeFunction) {
        List<T> result = new ArrayList<>();
        for (T t : list) {
            //ID
            String id = tTreeFunction.getIdColumn().apply(t);
            String parentId = tTreeFunction.getParentColumn().apply(t);
            List<String> checkIds = tTreeFunction.getCheckedIds();
            List<T> apply = tTreeFunction.getChildrenAction().apply(t);
            if (parentId == null || "".equals(parentId) || "0".equals(parentId) || (parentId != null && parentId.equals(tTreeFunction.getParentId()))) {
                if (checkIds != null && !checkIds.isEmpty() && checkIds.contains(id)) {
                    tTreeFunction.getCheckedColumn().apply(t);
                }
                result.add(t);
            }

            for (T ts : list) {
                String sid = tTreeFunction.getIdColumn().apply(ts);
                String sparentId = tTreeFunction.getParentColumn().apply(ts);
                if (sparentId != null && id.equals(sparentId)) {
                    //这个地方不好创建对象放入，所以树结构对象默认创建一个数组
                    if (apply != null) {
                        if (checkIds != null && !checkIds.isEmpty() && checkIds.contains(sid)) {
                            tTreeFunction.getCheckedColumn().apply(ts);
                        }
                        apply.add(ts);
                    }
                }
            }
        }
        return result;
    }
}
